<?php


namespace App\Services;

use App\Models\Category;

class CategoryService
{
    // 获取栏目树
    public function getCategoryTree($parentId = null, $allCategories = null)
    {
        if (is_null($allCategories)) {
            $allCategories = Category::all();
        }

        return $allCategories->where('parent_id', $parentId)
            ->map(function ($category) use ($allCategories) {
                $data = ['id' => $category->id, 'name' => $category->name];
                if (!$category->is_directory) {
                    return $data;
                }
                // 否者递归调用
                $data['children'] = $this->getCategoryTree($category->id, $allCategories);

                return $data;
        });
    }

    // 返回适配webapp商城的api  api标准: http://demo.rageframe.com/api/tiny-shop/v1/product/cate/index
    public function getCategoryTreeToWebApp($parentId = null, $allCategories = null)
    {
        if (is_null($allCategories)) {
            $allCategories = Category::all();
        }

        return $allCategories->where('parent_id', $parentId)
            ->map(function ($category) use ($allCategories) {
                $data = ['id' => $category->id, 'title' => $category->name];
                if (!$category->is_directory) {
                    return $data;
                }
                // 递归调用
                $data['child'] = $this->getCategoryTreeToWebApp($category->id, $allCategories)->values();

                return $data;
            })->values();
    }
}
